<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import axios from 'axios'
import request from '@/utils/request'
// 引入 ECharts
import * as echarts from 'echarts'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const courseInfo = ref({
  id: null,
  name: '课程知识图谱'
})
const graphData = ref(null)
const selectedCourses = ref([])
const selectedCourseId = ref(null)
const loadingCourses = ref(false)
const graphChart = ref(null)
let chartInstance = null

// 所有课程列表和加载状态
const allCourses = ref([])
const loadingAllCourses = ref(false)

// 加载所有可选课程
const loadAllCourses = async () => {
  if (allCourses.value.length > 0) return

  loadingAllCourses.value = true
  try {
    const { data } = await request.get('/api/student/course-selection/')
    allCourses.value = data
    console.log('获取所有课程:', allCourses.value)

    // 如果返回的数据为空或格式不对，使用测试数据
    if (!Array.isArray(allCourses.value) || allCourses.value.length === 0) {
      useDefaultCourses()
    }
  } catch (error) {
    console.error('获取所有课程失败:', error)
    ElMessage.error('加载课程列表失败，将使用测试数据')
    // 使用默认测试数据
    useDefaultCourses()
  } finally {
    loadingAllCourses.value = false
  }
}

// 使用默认课程数据
const useDefaultCourses = () => {
  console.log('使用默认课程数据')
  allCourses.value = [
    { id: 1, name: '数据结构', description: '计算机科学中的基础课程，研究数据的组织和存储方式' },
    { id: 2, name: '操作系统', description: '管理计算机硬件与软件资源的系统软件' },
    { id: 3, name: '计算机网络', description: '研究计算机网络的原理和技术' },
    { id: 4, name: '数据库系统', description: '管理和存储数据的专用软件系统' },
    { id: 5, name: '软件工程', description: '应用工程化方法构建和维护高质量软件的学科' },
    { id: 6, name: '人工智能', description: '研究如何使计算机模拟人类智能的科学' }
  ]
}

// 生成知识图谱可视化
const renderGraph = async () => {
  if (!graphData.value || !graphData.value.nodes || !graphData.value.edges) return

  await nextTick()

  // 销毁旧的图表实例
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }

  // 初始化图表
  const chartDom = document.getElementById('graphChart')
  if (!chartDom) {
    console.error('找不到图表DOM元素')
    return
  }

  chartInstance = echarts.init(chartDom)
  console.log('创建新的图表实例')

  // 准备节点和边数据
  const nodes = graphData.value.nodes.map(node => ({
    id: node.id,
    name: node.label,
    value: node.level,
    category: node.level - 1, // 根据level分类
    symbolSize: node.level === 1 ? 50 : (node.level === 2 ? 35 : 25), // 根据层级确定大小
    itemStyle: {
      color: node.level === 1 ? '#ff7d00' : (node.level === 2 ? '#3fa7dc' : '#59c067') // 根据层级设置颜色
    }
  }))

  // 准备边数据
  const edges = graphData.value.edges.map(edge => ({
    source: edge.source,
    target: edge.target,
    value: edge.relation || 'related'
  }))

  // 图表配置
  const option = {
    title: {
      text: `${courseInfo.value.name} - 知识图谱`,
      top: 'top',
      left: 'center',
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        if (params.dataType === 'node') {
          return `<div style="font-weight:bold">${params.data.name}</div>级别: ${params.data.value}`
        } else {
          return `${params.data.source} → ${params.data.target}`
        }
      }
    },
    legend: {
      data: ['课程', '章节', '知识点'],
      bottom: 'bottom'
    },
    animationDuration: 1500,
    animationEasingUpdate: 'quinticInOut',
    series: [{
      type: 'graph',
      layout: 'force',
      data: nodes,
      links: edges,
      edgeSymbol: ['none', 'arrow'],
      categories: [
        { name: '课程' },
        { name: '章节' },
        { name: '知识点' }
      ],
      roam: true,
      label: {
        show: true,
        position: 'right',
        formatter: '{b}'
      },
      force: {
        repulsion: 150,
        edgeLength: [80, 150]
      },
      emphasis: {
        focus: 'adjacency',
        lineStyle: {
          width: 4
        }
      }
    }]
  }

  // 设置图表
  chartInstance.setOption(option)
  console.log('图表渲染完成')

  // 移除之前可能存在的事件监听器，避免重复添加
  window.removeEventListener('resize', chartInstance?.resize)
  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    if (chartInstance) {
      chartInstance.resize()
    }
  })
}

// 监听图谱数据变化，渲染图表
watch(() => graphData.value, () => {
  if (graphData.value) {
    renderGraph()
  }
})

// 监听选择的课程ID变化
watch(() => selectedCourseId.value, (newId, oldId) => {
  if (newId && newId !== oldId) {
    console.log(`课程ID变更: ${oldId} -> ${newId}，加载新知识图谱`);
    // 清除之前的图表实例
    destroyChart();
    // 加载新选择的课程知识图谱
    loadKnowledgeGraph(newId);
  }
})

// 获取学生信息
const getStudentInfo = () => {
  try {
    const rawInfo = localStorage.getItem('studentUserInfo')
    if (!rawInfo) throw new Error('无登录信息')

    const userInfo = JSON.parse(rawInfo)
    if (!userInfo?.stu_id && !userInfo?.username) {
      localStorage.removeItem('studentUserInfo')
      router.push('/student/login')
      return null
    }
    return userInfo
  } catch (e) {
    console.error('学生信息获取失败:', e)
    return null
  }
}

// 检查课程是否已选
const isCourseSelected = (courseId) => {
  return selectedCourses.value.some(course => course.id === courseId)
}

// 选择或取消选择课程
const toggleCourseSelection = async (courseId, isSelected) => {
  const userInfo = getStudentInfo()
  if (!userInfo) return

  try {
    if (isSelected) {
      // 选择课程
      await request.post('/api/student/course-selection/', {
        course_id: courseId,
        username: userInfo.username || userInfo.stu_id
      })
      ElMessage.success('已选择课程')

      // 更新已选课程列表
      const course = allCourses.value.find(c => c.id === courseId)
      if (course && !selectedCourses.value.some(c => c.id === courseId)) {
        selectedCourses.value.push(course)
      }
    } else {
      // 取消选择课程
      await request.delete(`/api/student/course-selection/${courseId}/`, {
        params: {
          username: userInfo.username || userInfo.stu_id
        }
      })
      ElMessage.success('已取消选择课程')

      // 更新已选课程列表
      selectedCourses.value = selectedCourses.value.filter(course => course.id !== courseId)

      // 如果当前正在查看的就是这个被取消的课程，则切换到其他课程
      if (selectedCourseId.value === courseId) {
        if (selectedCourses.value.length > 0) {
          selectedCourseId.value = selectedCourses.value[0].id
          loadKnowledgeGraph(selectedCourseId.value)
        } else {
          graphData.value = null
          courseInfo.value = { id: null, name: '课程知识图谱' }
        }
      }
    }
  } catch (error) {
    console.error('课程选择操作失败:', error)
    ElMessage.error('课程选择操作失败，请重试')
  }
}

// 加载用户已选课程
const loadSelectedCourses = async () => {
  const userInfo = getStudentInfo()
  if (!userInfo) {
    console.log('未获取到用户信息，使用默认课程数据')
    useDefaultSelectedCourses()
    return
  }

  loadingCourses.value = true
  try {
    // 请求参数设置
    const params = {}
    if (userInfo.username) {
      params.username = userInfo.username
    } else if (userInfo.stu_id) {
      params.stu_id = userInfo.stu_id
    }

    console.log('请求已选课程，参数:', params)

    // 获取已选课程
    const { data: selectedCourseIds } = await request.get('/api/student/course-selection/', {
      params,
      timeout: 5000 // 设置超时
    })
    console.log('已选课程IDs:', selectedCourseIds)

    // 处理获取到的课程数据
    if (Array.isArray(selectedCourseIds) && selectedCourseIds.length > 0) {
      // 检查allCourses是否已加载
      if (allCourses.value.length === 0) {
        await loadAllCourses();
      }

      // 过滤出已选课程
      selectedCourses.value = allCourses.value.filter(course =>
        selectedCourseIds.includes(course.id) || // 直接包含ID
        (typeof selectedCourseIds[0] === 'object' && selectedCourseIds.some(item => item.course_id === course.id)) // 或者是对象数组中的course_id
      )

      console.log('已过滤出的已选课程:', selectedCourses.value)

      // 如果未能找到课程详情，使用默认数据
      if (selectedCourses.value.length === 0 && selectedCourseIds.length > 0) {
        console.log('未能匹配到已选课程详情，使用默认数据')
        useDefaultSelectedCourses(selectedCourseIds)
      }
    } else {
      // 如果没有获取到任何已选课程，使用默认测试数据
      console.log('没有获取到已选课程数据，将显示所有课程')
      selectedCourses.value = [];
    }
  } catch (error) {
    console.error('加载已选课程失败:', error)
    ElMessage.error('获取已选课程失败')
    selectedCourses.value = [];
  } finally {
    loadingCourses.value = false
  }
}

// 处理选择的课程
const processSelectedCourse = () => {
  console.log('处理选择的课程')

  // 如果没有任何课程，无法选择
  if (allCourses.value.length === 0) {
    console.log('没有可选的课程')
    return
  }

  // 如果有路由参数中的课程ID，优先使用
  if (route.params.courseId) {
    selectedCourseId.value = Number(route.params.courseId)
    console.log(`从路由参数选择课程ID: ${selectedCourseId.value}`)
  }
  // 否则，如果之前已经选择了课程，保持选择
  else if (selectedCourseId.value && allCourses.value.some(c => c.id === selectedCourseId.value)) {
    console.log(`保持已选择的课程ID: ${selectedCourseId.value}`)
  }
  // 否则默认选择第一个课程
  else if (allCourses.value.length > 0) {
    selectedCourseId.value = allCourses.value[0].id
    console.log(`默认选择第一个课程ID: ${selectedCourseId.value}`)
  }

  // 加载选择的课程知识图谱
  if (selectedCourseId.value) {
    loadKnowledgeGraph(selectedCourseId.value)
  }
}

// 使用默认已选课程数据
const useDefaultSelectedCourses = (courseIds) => {
  console.log('使用默认已选课程数据')

  // 如果提供了courseIds，则根据courseIds构建默认数据
  if (courseIds && courseIds.length > 0) {
    // 根据courseIds构建课程数据
    selectedCourses.value = courseIds.map((item, index) => {
      const courseId = typeof item === 'object' ? item.course_id : item
      return {
        id: courseId,
        name: `课程${courseId}`,
        description: `测试课程${courseId}的描述`
      }
    })
  } else {
    // 使用完全默认的数据
    selectedCourses.value = [
      { id: 1, name: '数据结构', description: '计算机科学中的基础课程' },
      { id: 3, name: '计算机网络', description: '研究计算机网络的原理和技术' }
    ]
  }

  console.log('默认已选课程:', selectedCourses.value)
}

// 切换选择的课程
const handleCourseChange = (courseId) => {
  console.log(`用户选择了课程ID: ${courseId}`);
  if (selectedCourseId.value !== courseId) {
    selectedCourseId.value = courseId;

    // 更新课程信息
    const selectedCourse = allCourses.value.find(c => c.id === Number(courseId));
    if (selectedCourse) {
      courseInfo.value = {
        id: courseId,
        name: selectedCourse.name
      };
    }

    // 立即加载新选择的课程知识图谱
    loadKnowledgeGraph(courseId);

    // 更新URL，不刷新页面
    router.push({
      name: route.name,
      params: { ...route.params, courseId }
    });
  }
}

// 加载课程图谱数据
const loadKnowledgeGraph = async (courseId) => {
  if (!courseId) {
    ElMessage.warning('请先选择一门课程')
    return
  }

  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在加载知识图谱...',
    background: 'rgba(255, 255, 255, 0.7)'
  })

  loading.value = true
  // 清空之前的图谱数据
  graphData.value = null

  try {
    console.log(`加载课程 ${courseId} 的知识图谱数据`)

    // 获取学生信息
    const userInfo = getStudentInfo()
    if (!userInfo) {
      // 没有学生信息，使用测试数据
      useDefaultGraphData(courseId)
      return
    }

    // 设置课程信息
    const selectedCourse = allCourses.value.find(c => c.id === Number(courseId))
    if (selectedCourse) {
      courseInfo.value = {
        id: courseId,
        name: selectedCourse.name
      }
    } else {
      // 尝试获取课程信息，失败则使用默认信息
      try {
        const { data } = await request.get(`/api/student/course/${courseId}/`)
        courseInfo.value = {
          id: courseId,
          name: data.name || data.course_name || `课程${courseId}`
        }
      } catch (error) {
        console.error('获取课程信息失败:', error)
        courseInfo.value.name = `课程${courseId}`
      }
    }

    // 尝试获取知识图谱数据
    try {
      console.log(`请求课程${courseId}的知识图谱API`)

      // 使用课程ID路径参数，而不是查询参数
      const { data } = await request.get(`/api/student/course/${courseId}/knowledge-graph/`, {
        timeout: 5000 // 设置超时时间
      })

      console.log('API返回知识图谱数据:', data)

      // 检查返回的数据格式
      if (data && data.nodes && data.nodes.length > 0 && data.edges && data.edges.length > 0) {
        graphData.value = data
        console.log('使用API返回的知识图谱数据')
      } else if (data && data.data && data.data.nodes && data.data.nodes.length > 0) {
        graphData.value = data.data
        console.log('使用API返回data字段中的知识图谱数据')
      } else {
        // 返回数据格式不正确或为空，使用测试数据
        console.log('API返回数据格式不符合要求，使用测试数据')
        useDefaultGraphData(courseId)
      }
    } catch (error) {
      console.error('获取知识图谱数据失败:', error)
      // 使用默认模拟数据
      console.log('API请求失败，使用测试数据')
      useDefaultGraphData(courseId)
    }
  } catch (e) {
    console.error('加载知识图谱过程中出错:', e)
    ElMessage.error('加载知识图谱失败，使用测试数据')
    // 出现任何错误，使用默认数据
    useDefaultGraphData(courseId)
  } finally {
    loading.value = false
    loadingInstance.close()

    // 确保在数据加载完成后渲染图表
    await nextTick()
    if (graphData.value) {
      renderGraph()
    }
  }
}

// 使用默认模拟数据
const useDefaultGraphData = (courseId) => {
  console.log('使用默认知识图谱数据，课程ID:', courseId);

  // 根据课程ID生成不同的默认图谱数据
  let nodes = [];
  let edges = [];

  // 将courseId转换为数字确保比较正确
  const courseIdNum = Number(courseId);

  if (courseIdNum === 1) { // 数据结构
    nodes = [
      { id: '1', label: '数据结构基础', level: 1 },
      { id: '2', label: '线性表', level: 2 },
      { id: '3', label: '栈与队列', level: 2 },
      { id: '4', label: '树结构', level: 2 },
      { id: '5', label: '图结构', level: 2 },
      { id: '6', label: '数组', level: 3 },
      { id: '7', label: '链表', level: 3 },
      { id: '8', label: '二叉树', level: 3 },
      { id: '9', label: '平衡树', level: 3 },
      { id: '10', label: '最短路径', level: 3 }
    ];

    edges = [
      { source: '1', target: '2' },
      { source: '1', target: '3' },
      { source: '1', target: '4' },
      { source: '1', target: '5' },
      { source: '2', target: '6' },
      { source: '2', target: '7' },
      { source: '4', target: '8' },
      { source: '4', target: '9' },
      { source: '5', target: '10' }
    ];
  }
  else if (courseIdNum === 2) { // 操作系统
    nodes = [
      { id: '1', label: '操作系统概述', level: 1 },
      { id: '2', label: '进程管理', level: 2 },
      { id: '3', label: '内存管理', level: 2 },
      { id: '4', label: '文件系统', level: 2 },
      { id: '5', label: '设备管理', level: 2 },
      { id: '6', label: '进程调度', level: 3 },
      { id: '7', label: '死锁', level: 3 },
      { id: '8', label: '虚拟内存', level: 3 },
      { id: '9', label: 'Linux文件系统', level: 3 },
      { id: '10', label: 'I/O系统', level: 3 }
    ];

    edges = [
      { source: '1', target: '2' },
      { source: '1', target: '3' },
      { source: '1', target: '4' },
      { source: '1', target: '5' },
      { source: '2', target: '6' },
      { source: '2', target: '7' },
      { source: '3', target: '8' },
      { source: '4', target: '9' },
      { source: '5', target: '10' }
    ];
  }
  else if (courseIdNum === 3) { // 计算机网络
    nodes = [
      { id: '1', label: '网络基础', level: 1 },
      { id: '2', label: '物理层', level: 2 },
      { id: '3', label: '数据链路层', level: 2 },
      { id: '4', label: '网络层', level: 2 },
      { id: '5', label: '传输层', level: 2 },
      { id: '6', label: '应用层', level: 2 },
      { id: '7', label: 'IP协议', level: 3 },
      { id: '8', label: 'TCP协议', level: 3 },
      { id: '9', label: 'HTTP协议', level: 3 },
      { id: '10', label: 'DNS系统', level: 3 }
    ];

    edges = [
      { source: '1', target: '2' },
      { source: '1', target: '3' },
      { source: '1', target: '4' },
      { source: '1', target: '5' },
      { source: '1', target: '6' },
      { source: '4', target: '7' },
      { source: '5', target: '8' },
      { source: '6', target: '9' },
      { source: '6', target: '10' }
    ];
  }
  else if (courseIdNum === 4) { // 数据库系统
    nodes = [
      { id: '1', label: '数据库系统概论', level: 1 },
      { id: '2', label: '关系模型', level: 2 },
      { id: '3', label: 'SQL', level: 2 },
      { id: '4', label: '数据库设计', level: 2 },
      { id: '5', label: '事务处理', level: 2 },
      { id: '6', label: '关系代数', level: 3 },
      { id: '7', label: '高级SQL', level: 3 },
      { id: '8', label: 'ER模型', level: 3 },
      { id: '9', label: '并发控制', level: 3 },
      { id: '10', label: '恢复技术', level: 3 }
    ];

    edges = [
      { source: '1', target: '2' },
      { source: '1', target: '3' },
      { source: '1', target: '4' },
      { source: '1', target: '5' },
      { source: '2', target: '6' },
      { source: '3', target: '7' },
      { source: '4', target: '8' },
      { source: '5', target: '9' },
      { source: '5', target: '10' }
    ];
  }
  else if (courseIdNum === 5) { // 软件工程
    nodes = [
      { id: '1', label: '软件工程概述', level: 1 },
      { id: '2', label: '软件需求', level: 2 },
      { id: '3', label: '软件设计', level: 2 },
      { id: '4', label: '软件测试', level: 2 },
      { id: '5', label: '软件维护', level: 2 },
      { id: '6', label: '需求分析', level: 3 },
      { id: '7', label: '架构设计', level: 3 },
      { id: '8', label: '详细设计', level: 3 },
      { id: '9', label: '单元测试', level: 3 },
      { id: '10', label: '集成测试', level: 3 }
    ];

    edges = [
      { source: '1', target: '2' },
      { source: '1', target: '3' },
      { source: '1', target: '4' },
      { source: '1', target: '5' },
      { source: '2', target: '6' },
      { source: '3', target: '7' },
      { source: '3', target: '8' },
      { source: '4', target: '9' },
      { source: '4', target: '10' }
    ];
  }
  else if (courseIdNum === 6) { // 人工智能
    nodes = [
      { id: '1', label: '人工智能基础', level: 1 },
      { id: '2', label: '机器学习', level: 2 },
      { id: '3', label: '神经网络', level: 2 },
      { id: '4', label: '自然语言处理', level: 2 },
      { id: '5', label: '计算机视觉', level: 2 },
      { id: '6', label: '监督学习', level: 3 },
      { id: '7', label: '深度学习', level: 3 },
      { id: '8', label: '语言模型', level: 3 },
      { id: '9', label: '图像识别', level: 3 },
      { id: '10', label: '强化学习', level: 3 }
    ];

    edges = [
      { source: '1', target: '2' },
      { source: '1', target: '3' },
      { source: '1', target: '4' },
      { source: '1', target: '5' },
      { source: '2', target: '6' },
      { source: '3', target: '7' },
      { source: '4', target: '8' },
      { source: '5', target: '9' },
      { source: '2', target: '10' }
    ];
  }
  else {
    // 通用图谱 - 根据课程ID生成一些随机变化
    const courseIdStr = String(courseIdNum);
    const seed = courseIdNum * 100;

    // 根据课程ID生成不同的节点数量(4-8个)
    const nodeCount = 4 + (courseIdNum % 5);

    // 生成节点
    nodes.push({ id: '1', label: `课程${courseIdNum}基础`, level: 1 });

    for (let i = 2; i <= nodeCount; i++) {
      const level = i <= 4 ? 2 : 3;
      nodes.push({
        id: String(i),
        label: `主题${i-1}`,
        level
      });
    }

    // 生成边 - 将第一个节点连到所有2级节点
    for (let i = 2; i <= Math.min(5, nodeCount); i++) {
      edges.push({ source: '1', target: String(i) });
    }

    // 将2级节点连到3级节点
    for (let i = 5; i <= nodeCount; i++) {
      const sourceIdx = 2 + (i % 3); // 将3级节点连到不同的2级节点
      edges.push({ source: String(sourceIdx), target: String(i) });
    }
  }

  graphData.value = { nodes, edges };
}

// 返回课程页面
const backToCourse = () => {
  router.push('/student/Homepage/SelectedCourse')
}

// 监听路由参数变化
watch(
  () => route.params.courseId,
  (newId) => {
    if (newId) {
      console.log(`路由参数课程ID变更为: ${newId}`);
      if (selectedCourseId.value !== Number(newId)) {
        selectedCourseId.value = Number(newId)
        loadKnowledgeGraph(newId)
      }
    } else {
      console.log('路由无课程ID参数，保持当前选择状态');
    }
  }
)

// 组件卸载时清理资源
const destroyChart = () => {
  if (chartInstance) {
    console.log('销毁图表实例')
    chartInstance.dispose()
    chartInstance = null
    // 移除窗口大小变化监听
    window.removeEventListener('resize', () => chartInstance?.resize)
  }
}

// 组件挂载时加载数据
onMounted(async () => {
  try {
    console.log('加载知识图谱页面...');

    // 首先加载所有课程
    await loadAllCourses();
    console.log('已加载所有课程:', allCourses.value.length);

    // 再加载已选课程（只用于显示已选课程数量信息）
    await loadSelectedCourses();
    console.log('已加载已选课程:', selectedCourses.value.length);

    // 处理选择课程
    processSelectedCourse();
  } catch (error) {
    console.error('初始化知识图谱页面失败:', error);
    ElMessage.error('加载页面数据失败，将使用测试数据');

    // 确保至少加载所有课程的测试数据
    useDefaultCourses();

    // 尝试从路由参数加载课程
    if (route.params.courseId) {
      selectedCourseId.value = Number(route.params.courseId);
      loadKnowledgeGraph(selectedCourseId.value);
    } else if (allCourses.value.length > 0) {
      // 否则加载第一个课程
      selectedCourseId.value = allCourses.value[0].id;
      loadKnowledgeGraph(selectedCourseId.value);
    }
  }
})

// 组件卸载时清理资源
onUnmounted(() => {
  destroyChart()
})

// 手动重新加载当前课程的知识图谱
const reloadCurrentGraph = () => {
  if (selectedCourseId.value) {
    ElMessage.info('正在重新加载知识图谱...')
    // 清除之前的图表实例
    destroyChart();
    // 重新加载知识图谱
    loadKnowledgeGraph(selectedCourseId.value)
  } else {
    ElMessage.warning('请先选择一门课程')
  }
}

// 切换聊天窗口显示/隐藏
const toggleChat = () => {
    const container = document.getElementById('chatContainer');
    if (container.style.display === 'none' || container.style.display === '') {
        container.style.display = 'block';
    } else {
        container.style.display = 'none';
    }
}

</script>

<template>
  <div class="knowledge-graph-container">
    <header class="graph-header">
      <div class="back-button">
        <el-button type="primary" plain @click="backToCourse">返回主页</el-button>
      </div>
      <h1 class="graph-title">{{ courseInfo.name }} - 知识图谱</h1>
    </header>

    <!-- 课程选择区域 -->
    <div class="course-selection-container">
      <el-row :gutter="20">
        <el-col :span="14">
          <el-select
            v-model="selectedCourseId"
            placeholder="请选择课程"
            @change="handleCourseChange"
            style="width: 100%"
            v-loading="loadingAllCourses"
          >
            <el-option
              v-for="course in allCourses"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <div v-if="selectedCourses.length > 0" class="selected-course-info">
            已选择 {{ selectedCourses.length }} 门课程
          </div>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="reloadCurrentGraph" :loading="loading" size="default">
            刷新图谱
          </el-button>
        </el-col>
      </el-row>
    </div>

    <main class="graph-content">
      <div v-if="loading" class="loading-placeholder">
        <el-skeleton :rows="10" animated />
      </div>

      <div v-else-if="!graphData" class="empty-state">
        <el-empty description="暂无知识图谱数据" />
        <p>请选择一个课程查看其知识图谱</p>
      </div>

      <div v-else class="graph-visualization">
        <!-- 图谱信息摘要 -->
        <div class="graph-info">
          <p>当前课程知识图谱包含 {{ graphData.nodes.length }} 个知识点，{{ graphData.edges.length }} 个连接关系</p>
        </div>

        <!-- 图谱可视化区域 -->
        <div class="graph-visual-container">
          <div id="graphChart" class="graph-chart" ref="graphChart"></div>

          <!-- 知识点列表 -->
          <div class="knowledge-lists">
            <div class="node-list">
              <h3>知识点列表</h3>
              <el-scrollbar height="300px">
                <div v-for="node in graphData.nodes" :key="node.id" class="node-item">
                  <div class="node-label">{{ node.label }}</div>
                  <div class="node-level">Level: {{ node.level }}</div>
                </div>
              </el-scrollbar>
            </div>

            <div class="edge-list">
              <h3>知识联系</h3>
              <el-scrollbar height="300px">
                <div v-for="(edge, index) in graphData.edges" :key="index" class="edge-item">
                  <div class="edge-source">{{ graphData.nodes.find(n => n.id === edge.source)?.label }}</div>
                  <div class="edge-arrow">→</div>
                  <div class="edge-target">{{ graphData.nodes.find(n => n.id === edge.target)?.label }}</div>
                </div>
              </el-scrollbar>
            </div>
          </div>
        </div>
      </div>
    </main>

    <footer class="graph-footer">
      <p>本图谱展示了课程中知识点之间的联系，帮助您更好地理解学习内容</p>
    </footer>
  </div>
<!--  <div class="chat-bubble" @click="toggleChat">-->
<!--        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z'/%3E%3C/svg%3E" alt="聊天">-->
<!--    </div>-->

<!--    <div class="chat-container" id="chatContainer">-->
<!--        <iframe src="http://121.40.242.43/chatbot/W6TLrJcFFhFE1Zpi" class="chat-iframe"></iframe>-->
<!--    </div>-->
</template>

<style scoped>
.knowledge-graph-container {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.graph-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  position: relative;
}

.back-button {
  position: absolute;
  left: 0;
}

.graph-title {
  flex: 1;
  text-align: center;
  margin: 0;
  font-size: 24px;
  color: #333;
}

.course-selection-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.course-count, .selected-course-info {  line-height: 40px;  color: #606266;  font-size: 14px;}

.graph-content {
  flex: 1;
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 20px;
  overflow: auto;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.graph-visualization {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.graph-info {
  background-color: #fff;
  padding: 15px;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.graph-visual-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.graph-chart {
  height: 400px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.knowledge-lists {
  display: flex;
  gap: 20px;
}

.node-list, .edge-list {
  background-color: #fff;
  padding: 15px;
  border-radius: 6px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  flex: 1;
}

.node-item, .edge-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
}

.node-item:hover, .edge-item:hover {
  background-color: #f0f7ff;
}

.node-label {
  font-weight: bold;
  color: #409EFF;
}

.node-level {
  margin-left: auto;
  color: #909399;
  font-size: 0.9em;
}

.edge-source {
  color: #409EFF;
  font-weight: bold;
}

.edge-arrow {
  margin: 0 10px;
  color: #E6A23C;
  font-weight: bold;
}

.edge-target {
  color: #67C23A;
  font-weight: bold;
}

.graph-footer {
  margin-top: 20px;
  text-align: center;
  color: #909399;
  font-size: 0.9em;
}

.loading-placeholder, .empty-state {
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-state p {
  margin-top: 20px;
  color: #909399;
}

.course-manager {
  padding: 15px;
}

.course-manager h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #606266;
}

.selected-course-info {
  line-height: 40px;
  color: #606266;
  font-size: 14px;
  padding-left: 10px;
}
.chat-bubble {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 60px;
    height: 60px;
    background-color: #007bff;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    z-index: 1000;
}

.chat-bubble img {
    width: 30px;
    height: 30px;
}

.chat-container {
    position: fixed;
    bottom: 100px;
    right: 20px;
    width: 350px;
    height: 500px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    display: none;
    z-index: 999;
}

.chat-iframe {
    width: 100%;
    height: 100%;
    border: none;
    border-radius: 10px;
}
</style>
